package com.bawei.a2010douyin.week3.ui.main;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import android.os.Bundle;

import com.bawei.a2010douyin.R;
import com.bawei.a2010douyin.base.mvp.BaseActivity;
import com.bawei.a2010douyin.base.mvp.BaseMvpActivity;
import com.bawei.a2010douyin.db.dao.DBUtils;
import com.bawei.a2010douyin.entity.VideoEntity;
import com.bawei.a2010douyin.week3.entity.Video;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.List;

public class Week3MainActivity extends BaseMvpActivity<MainContract.IMainView,MainPresenter> implements MainContract.IMainView{
    private SmartRefreshLayout smart;
    private RecyclerView rv;
    private VideoAdapter mVideoAdapter;

    private int page = 1;


    @Override
    public int bindLayout() {
        return R.layout.activity_week3_main;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        smart = (SmartRefreshLayout) findViewById(R.id.smart);
        rv = (RecyclerView) findViewById(R.id.rv);
        mVideoAdapter = new VideoAdapter(R.layout.item_week3);
        rv.setAdapter(mVideoAdapter);
        rv.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));

        smart.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                mPresenter.video(page,10);
                smart.finishLoadMore();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                mVideoAdapter.getData().clear();
                mPresenter.video(page,10);
                smart.finishRefresh();
            }
        });
    }

    @Override
    public MainPresenter createPresenter() {
        return new MainPresenter();
    }

    @Override
    public void initData() {
        mPresenter.video(1,10);
    }

    @Override
    public void showVideo(List<VideoEntity> data) {
        mVideoAdapter.getData().addAll(data);
        mVideoAdapter.notifyDataSetChanged();
        //数据库缓存
        for (VideoEntity datum : data) {
            Video video = new Video();
            video.setId(datum.getId());
            video.setAuthname(datum.getAuthname());
            video.setCaption(datum.getCaption());
            video.setHeadpath(datum.getHeadpath());
            DBUtils.getInstance().insertVideo(video);
        }
    }
}